<template>
  <div class="production-plan">
    <!-- 头部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">保存</el-button>
      <el-button type="primary" @click="get">返回列表</el-button>
    </div>

    <!-- 基本信息区域 -->
    <div class="production-plan-form">
      <el-form :model="formData" :label-width="120">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据编码">
              <el-input v-model="formData.documentCode" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务类型">
              <el-select v-model="formData.businessType" disabled>
                <el-option label="生产计划" value="productionPlan"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-input v-model="formData.salesperson" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单BOM">
              <el-button
                type="text"
                @click="openProductSelector(materialList.materialCode)"
                >查看</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据日期">
              <el-date-picker
                v-model="formData.documentDate"
                type="date"
                style="width: 255px"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作员">
              <el-input v-model="formData.operator" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务单号">
              <el-input v-model="formData.businessOrderNo" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本号">
              <el-input v-model="formData.versionNumber" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据状态">
              <el-select v-model="formData.documentStatus">
                <el-option label="开立" value="开立"></el-option>
                <el-option label="审核" value="审核"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核员">
              <el-input v-model="formData.auditor" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单交期">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="选择日期"
                style="width: 255px"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本说明">
              <el-input v-model="formData.versionDescription"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务状态">
              <el-select v-model="formData.businessStatus" disabled>
                <el-option label="正常" value="normal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核日期">
              <el-date-picker
                v-model="formData.auditDate"
                type="date"
                placeholder="选择日期"
                style="width: 255px"
                disabled
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产总量">
              <el-input v-model="formData.productionTotal" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 订单信息表格 -->
    <div class="order-info">
      <h3>订单信息</h3>
      <br />
      <el-table :data="dialogProductList" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="mainUnit" label="主计量"></el-table-column>
        <el-table-column prop="demandquantity" label="数量"></el-table-column>
        <el-table-column
          prop="qualityRequirement"
          label="质量要求"
        ></el-table-column>
        <el-table-column
          prop="packagingRequirement"
          label="包装要求"
        ></el-table-column>
        <el-table-column
          prop="procurementInstructions"
          label="备注"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" link @click="deleteProduct(scope.row)"
              >删除</el-button
            >
            <el-button
              type="text"
              @click="getMaterialList(scope.row.materialCode)"
              >获取物料清单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 物料清单表格 -->
    <div class="material-list">
      <h3>物料清单</h3>
      <br />
      <el-table :data="materialListData" border>
        <el-table-column
          type="index"
          width="60px"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="billCode"
          width="110px"
          label="单据编码"
        ></el-table-column>
        <el-table-column prop="billStatus" label="单据状态"></el-table-column>
        <el-table-column
          prop="businessType"
          label="业务类型"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="billStatus"
          label="状态"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="materialCode"
          label="物料编码"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="materialName"
          label="物料名称"
          width="110px"
        ></el-table-column>
        <el-table-column
          prop="mainUnit"
          label="主计量"
          width="110px"
        ></el-table-column>
        <el-table-column prop="supplymode" label="供应方式" width="150px">
          <template #default="scope">
            <el-select
              v-model="scope.row.supplymode"
              placeholder="请选择供应方式"
            >
              <el-option label="委外" value="委外"></el-option>
              <el-option label="加工" value="加工"></el-option>
              <el-option label="生产" value="生产"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="productionQuantity"
          width="110px"
          label="生产数量"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.productionQuantity"
              placeholder="输入数量"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="workshop" label="下发车间" width="150px">
          <template v-slot="scope">
            <el-select v-model="scope.row.workshop" placeholder="请选择车间">
              <el-option label="装配车间" value="装配车间"></el-option>
              <el-option label="加工车间" value="加工车间"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350px">
          <template #default="scope">
            <el-switch v-model="scope.row.status"></el-switch>
            <el-button type="text" @click="openProductSelectors"
              >BOM补料</el-button
            >
            <el-button type="text" @click="openProductSelectors"
              >生产补料</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 补料清单表格 -->
    <div class="supplementary-list">
      <h3>补料清单</h3>
      <el-button type="text" @click="handleAdds">保存</el-button>
      <br />
      <br />
      <el-table :data="supplementaryListData" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="billCode" label="单据编码"></el-table-column>
        <el-table-column
          prop="businessStatus"
          label="单据状态"
        ></el-table-column>
        <el-table-column prop="businessType" label="业务类型"></el-table-column>
        <el-table-column prop="billStatus" label="状态"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="mainUnit" label="主计量"></el-table-column>
        <el-table-column prop="supplymode" label="供应方式">
          <template #default="scope">
            <el-select
              v-model="scope.row.supplymode"
              placeholder="请选择供应方式"
            >
              <el-option label="采购" value="采购"></el-option>
              <el-option label="加工" value="加工"></el-option>
              <el-option label="委外" value="委外"></el-option>
              <el-option label="装配" value="装配"></el-option>
              <el-option label="生产" value="生产"></el-option>
              <el-option label="无" value="无"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="demandquantity" label="生产数量" width="150px">
          <template #default="scope">
            <el-input
              v-model="scope.row.demandquantity"
              placeholder="输入数量"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="reasonsForreplenishment"
          width="150px"
          label="补料事由"
          ><template #default="scope">
            <el-input
              v-model="scope.row.reasonsForreplenishment"
              placeholder="输入事由"
            ></el-input> </template
        ></el-table-column>
        <el-table-column prop="reasonsDate" width="250px" label="补料日期">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.reasonsDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="remark" width="150px" label="备注">
          <template #default="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="输入备注"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog
    title="选择订单"
    ref="dialogRef"
    v-model="dialogVisible"
    width="1200px"
  >
    <div class="search-bar">
      <el-input
        placeholder="请输入分类名称"
        v-model="searchCategory"
        prefix-icon="el-icon-search"
      ></el-input>
      <el-input placeholder="物料编码" v-model="searchCode"></el-input>
      <el-input placeholder="物料名称" v-model="searchName"></el-input>
      <el-button>连选</el-button>
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :data="materialList"
      border
      style="width: 1800px"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column
        prop="materialCode"
        label="物料编码"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="materialName"
        label="物料名称"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="modelSpec"
        label="型号规格"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="mainUnit"
        label="主计量"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="procurementInstructions"
        label="备注"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="demandquantity"
        label="数量"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="businessPerson"
        label="业务人员"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="billCode"
        label="业务单号"
        width="130"
      ></el-table-column>
      <el-table-column
        v-slot="scoped"
        prop="orderDeliveryDate"
        label="订单交期"
        width="120"
      >
        <!-- {{ scoped.row.creationDate.substring(0, 10) }} -->
        {{ scoped.row.orderDeliveryDate.substring(0, 10) }}
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <br />
    <div class="button-group">
      <el-button @click="closeDialog" class="action-button">关闭</el-button>
      <el-button type="primary" @click="confirmSelection" class="action-button"
        >选择</el-button
      >
    </div>
  </el-dialog>
  <el-dialog
    title="选择物料"
    ref="dialogRef"
    v-model="dialogVisible1"
    width="1200px"
  >
    <div class="search-bar">
      <el-input
        placeholder="销售订单号"
        v-model="searchParams.salesOrderNo"
        style="width: 150px"
      />
      <el-input
        placeholder="单据编码"
        v-model="searchParams.billCode"
        style="width: 150px"
      />
      <el-input
        placeholder="物料编码"
        v-model="searchParams.materialCode"
        style="width: 150px"
      />
      <el-input
        placeholder="物料名称"
        v-model="searchParams.materialName"
        style="width: 150px"
      />
      <el-date-picker
        v-model="searchParams.startDate"
        type="date"
        placeholder="开始日期"
        value-format="YYYY-MM-DD"
        style="width: 120px"
      />
      <el-date-picker
        v-model="searchParams.endDate"
        type="date"
        placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="width: 120px"
      />
      <el-button type="primary" @click="searchProducts">搜索</el-button>
    </div>
    <el-table
      @selection-change="handleSelectionChange1"
      :data="materialList"
      border
      style="width: 1800px"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column
        prop="materialCode"
        label="物料编码"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="materialName"
        label="物料名称"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="modelSpec"
        label="型号规格"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="mainUnit"
        label="主计量"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="procurementInstructions"
        label="备注"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="demandquantity"
        label="数量"
        width="200"
      ></el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="form1.PageIndex"
      v-model:page-size="form1.PageSize"
      :page-sizes="[1, 3, 15, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="form1.TotalCount"
      @size-change="handleSizeChange1"
      @current-change="handleCurrentChange1"
    />
    <br />
    <div class="button-group">
      <el-button @click="closeDialog" class="action-button">关闭</el-button>
      <el-button type="primary" @click="confirmSelection1" class="action-button"
        >选择</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
// const handleAudit = () => {
//   // 反填死数据：审核员固定为"系统审核员"，审核日期为当前日期
//   formData.auditor = "陈平安";
//   formData.auditDate = new Date();
//   ElMessage.success("审核成功");
// };
const get = () => {
  router.push("/GetProduce");
};
// 定义前端数据模型
const formData = reactive({
  documentCode: "",
  businessType: "productionPlan",
  salesperson: "",
  documentDate: "",
  operator: "",
  businessOrderNo: "",
  versionNumber: "",
  documentStatus: "",
  auditor: "",
  deliveryDate: null as Date | null,
  versionDescription: "",
  businessStatus: "normal",
  auditDate: null as Date | null,
  remark: "",
  productionTotal: "",
  materialCode: "",
});

// 提前定义 dialogProductList
const dialogProductList = ref<any[]>([]);
const dialogSelection = ref<any[]>([]);
const dialogSelection1 = ref<any[]>([]);
const supplementaryListData = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  dialogSelection.value = val;
};
const handleSelectionChange1 = (val: any[]) => {
  dialogSelection1.value = val;
};
const confirmSelection = () => {
  const selectedRows = dialogSelection.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    dialogProductList.value.push({
      materialCode: selectedProduct.materialCode,
      materialName: selectedProduct.materialName,
      modelSpec: selectedProduct.modelSpec,
      mainUnit: selectedProduct.mainUnit,
      demandquantity: selectedProduct.demandquantity, // 假设默认数量为1，可根据实际调整
      procurementInstructions: selectedProduct.procurementInstructions,
      businessPerson: selectedProduct.businessPerson,
      billCode: selectedProduct.billCode, // 假设默认数量为1，可根据实际调整
      orderDeliveryDate: selectedProduct.orderDeliveryDate,
    });
  });
  const totalQuantity = dialogProductList.value.reduce(
    (sum, item) => sum + (item.demandquantity || 0),
    0
  );
  formData.productionTotal = totalQuantity.toString();
  if (selectedRows.length > 0) {
    const firstRow = selectedRows[0]; // 假设取第一个选中行的相关字段，若有特殊逻辑可调整
    formData.salesperson = firstRow.businessPerson; // 业务员
    formData.businessOrderNo = firstRow.billCode; // 业务单号
    formData.deliveryDate = new Date(firstRow.orderDeliveryDate); // 订单交期，转换为Date类型以适配日期选择器
  }
  if (selectedRows.length > 0) {
    formData.materialCode = selectedRows[0].materialCode; // 按实际字段名调整
  }
  closeDialog();
};
// 搜索参数
const searchParams = reactive({
  salesOrderNo: "",
  billCode: "",
  materialCode: "",
  materialName: "",
  startDate: "", // 格式示例：'2023-10-01'
  endDate: "",
});
const confirmSelection1 = () => {
  const selectedRows = dialogSelection1.value;
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择产品");
    return;
  }
  selectedRows.forEach((selectedProduct) => {
    supplementaryListData.value.push({
      materialCode: selectedProduct.materialCode,
      materialName: selectedProduct.materialName,
      modelSpec: selectedProduct.modelSpec,
      mainUnit: selectedProduct.mainUnit,
      billCode: selectedProduct.billCode,
      billStatus: selectedProduct.billStatus,
      supplymode: selectedProduct.supplymode,
      businessType: selectedProduct.businessType,
      businessStatus: selectedProduct.businessStatus,
    });
  });
  closeDialog1();
};
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
const searchProductsS = () => {
  axios
    .get("http://localhost:5202/api/Log/GetERPMenu", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex, // 确保参数名与后端一致
        SalesOrderNo: searchParams.salesOrderNo,
        BillCode: searchParams.billCode,
        MaterialCode: searchParams.materialCode,
        MaterialName: searchParams.materialName,
        StartDate: searchParams.startDate,
        EndDate: searchParams.endDate,
      },
    })
    .then((res) => {
      materialList.value = res.data.data.list;
      // 注意：后端返回的总记录数是 Data.PageCount，但需要根据总记录数计算总页数
      form1.TotalCount = res.data.data.pageCount; // 总记录数
      form1.PageCount = Math.ceil(form1.TotalCount / form1.PageSize); // 前端计算总页数
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};

// 分页 - 每页数量变化
const handleSizeChange = (newSize: number, materialCode: string) => {
  form1.PageSize = newSize;
  searchProducts();
};

// 分页 - 当前页变化
const handleCurrentChange = (newPage: number, materialCode: string) => {
  form1.PageIndex = newPage;
  searchProducts();
};
// 分页 - 每页数量变化
const handleSizeChange1 = (newSize: number, materialCode: string) => {
  form1.PageSize = newSize;
  searchProductsS();
};

// 分页 - 当前页变化
const handleCurrentChange1 = (newPage: number, materialCode: string) => {
  form1.PageIndex = newPage;
  searchProductsS();
};
// 对话框可见性
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const closeDialog = () => {
  dialogVisible.value = false;
  dialogSelection.value = []; // 清空已选
};
const closeDialog1 = () => {
  dialogVisible1.value = false;
  dialogSelection1.value = []; // 清空已选
};

// 物料列表数据
const materialList = ref<any[]>([]);
const materialListData = ref<any[]>([]); // 物料清单数据
// 搜索条件
const searchCategory = ref("");
const searchCode = ref("");
const searchName = ref("");

// 打开物料选择对话框
const openProductSelector = async () => {
  dialogVisible.value = true;
  searchProducts();
};
// 打开补料物料选择对话框
const openProductSelectors = async () => {
  dialogVisible1.value = true;
  searchProductsS();
};
const searchProducts = () => {
  dialogVisible.value = true;
  axios
    .get("http://localhost:5202/api/Log/GetProcurement", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex,
      },
    })
    .then((res) => {
      materialList.value = res.data.data.list || [];
      form1.TotalCount = res.data.data.totalCount || 0;
      form1.PageCount = res.data.data.PageCount || 0;
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
      ElMessage.error("获取物料列表失败，请检查网络或重试");
    });
};

// 删除订单信息表格中的产品
const deleteProduct = (product) => {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const index = dialogProductList.value.indexOf(product);
      if (index !== -1) {
        dialogProductList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};
//物料清单反填
const getMaterialList = (materialCode: string) => {
  axios
    .get(
      `http://localhost:5202/api/Log/EditMaterialsBliiProcurement?materialCode=${materialCode}`
    )
    .then((res) => {
      materialListData.value = res.data.data || []; // 填充物料清单表格数据
    })
    .catch((error) => {
      console.error("获取物料清单失败", error);
      ElMessage.error("获取物料清单失败，请检查网络或重试");
    });
};
const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 12; i++) {
    // 生成12位数字
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};
// 定义与后端AddMultiTableDataCommand匹配的请求参数类型
interface ProductionPlanDto {
  DocumentCode: string;
  BusinessType: string;
  Salesperson: string;
  DocumentDate: string;
  Operator: string;
  BusinessOrderNo: string;
  VersionNumber: string;
  DocumentStatus: string;
  Auditor: string;
  DeliveryDate: string | null;
  VersionDescription: string;
  BusinessStatus: string;
  AuditDate: string | null;
  Remark: string;
  ProductionTotal: string;
  materialCode: string;
}
interface PlanReplenishMaterialsDto {
  BillCode: string;
  BusinessType: string;
  BusinessStatus: string;
  MaterialCode: string;
  BillStatus: string;
  MainUnit: string;
  Demandquantity: number;
  Supplymode: string;
  Remark: string;
  ReasonsForreplenishment: string;
  ReasonsDate: string | null; // 允许空日期
}
interface ProcurementMateialsDto {
  MaterialCode: string;
  MaterialName: string;
  ModelSpec: string;
  MainUnit: string;
  Demandquantity: number;
  ProcurementNum: number; // 前端需补充该字段（假设来自页面）
  RequiredDate: string; // 前端需补充该字段（假设来自页面）
  ProcurementInstructions: string;
}

interface PlanBillinfoDto {
  MaterialCode: string;
  MaterialName: string;
  ModelSpec: string;
  MainUnit: string;
  Demandquantity: number;
  Materialmethod: string; // 前端需补充该字段（假设来自页面）
  Supplymode: string;
  Workshop: string;
  Status: boolean; // 前端需补充该字段（假设来自页面）
}

interface AddMultiTableDataRequest {
  ProductionPlan: ProductionPlanDto;
  ProcurementMateials: ProcurementMateialsDto[];
  PlanBillinfo: PlanBillinfoDto[];
  PlanReplenishMaterials: PlanReplenishMaterialsDto[];
}
const handleAdd = async () => {
  try {
    // 整理生产计划数据（formData）
    const productionPlanDto: ProductionPlanDto = {
      DocumentCode: formData.documentCode,
      BusinessType: formData.businessType,
      Salesperson: formData.salesperson,
      DocumentDate: formData.documentDate,
      Operator: formData.operator,
      BusinessOrderNo: formData.businessOrderNo,
      VersionNumber: formData.versionNumber,
      DocumentStatus: formData.documentStatus,
      Auditor: formData.auditor,
      DeliveryDate: formData.deliveryDate
        ? dayjs(formData.deliveryDate).format("YYYY-MM-DD")
        : null,
      VersionDescription: formData.versionDescription,
      BusinessStatus: formData.businessStatus,
      AuditDate: formData.auditDate
        ? dayjs(formData.auditDate).format("YYYY-MM-DD")
        : null,
      Remark: formData.remark,
      ProductionTotal: formData.productionTotal,
      materialCode: formData.materialCode,
    };

    // 整理采购物料数据（dialogProductList）
    const procurementMateialsDto: ProcurementMateialsDto[] =
      dialogProductList.value.map((item) => ({
        MaterialCode: item.materialCode,
        MaterialName: item.materialName,
        ModelSpec: item.modelSpec,
        MainUnit: item.mainUnit,
        Demandquantity: Number(item.demandquantity),
        // 以下字段需根据前端页面补充（示例值，需替换为实际业务逻辑）
        ProcurementNum: Number(item.demandquantity), // 假设采购数量=需求数量
        RequiredDate: dayjs().format("YYYY-MM-DD"), // 假设需求日期为今日（需根据页面实际字段调整）
        ProcurementInstructions: item.procurementInstructions,
      }));

    // 整理计划单据数据（materialListData）
    const planBillinfoDto: PlanBillinfoDto[] = materialListData.value.map(
      (item) => ({
        MaterialCode: item.materialCode,
        MaterialName: item.materialName,
        ModelSpec: item.modelSpec,
        MainUnit: item.mainUnit,
        Demandquantity: Number(item.productionQuantity), // 假设需求数量=生产数量
        // 以下字段需根据前端页面补充（示例值，需替换为实际业务逻辑）
        Materialmethod: "默认方式", // 需根据页面实际字段调整
        Supplymode: item.supplymode,
        Workshop: item.workshop,
        Status: item.status, // 需根据页面实际字段调整
      })
    );

    // 整理补料清单数据（PlanReplenishMaterials）
    const planReplenishMaterialsDto: PlanReplenishMaterialsDto[] =
      supplementaryListData.value.map((item) => ({
        BillCode: item.billCode,
        BusinessType: item.businessType,
        BusinessStatus: item.businessStatus,
        MaterialCode: item.materialCode,
        BillStatus: item.billStatus,
        MainUnit: item.mainUnit,
        Demandquantity: item.demandquantity,
        Supplymode: item.supplymode,
        Remark: item.remark,
        ReasonsForreplenishment: item.reasonsForreplenishment,
        ReasonsDate: item.reasonsDate
          ? dayjs(item.reasonsDate).format("YYYY-MM-DD")
          : null,
      }));

    // 构造完整请求体
    const requestBody: AddMultiTableDataRequest = {
      ProductionPlan: productionPlanDto,
      ProcurementMateials: procurementMateialsDto,
      PlanBillinfo: planBillinfoDto,
      PlanReplenishMaterials: planReplenishMaterialsDto,
    };
    console.log(requestBody);
    // 调用后端API（假设后端接口地址为 /api/AddMultiTableData）
    const response = await axios.post(
      "http://localhost:5027/api/Log/UpdateMultiTableData",
      requestBody
    );

    if (response.data.code === 300) {
      ElMessage.success("修改成功");
      router.push("/GetProduce");
    } else {
      ElMessage.error(`修改成功${response.data.message}`);
    }
  } catch (error) {
    ElMessage.error("保存失败：网络请求异常");
  }
};

const handleView = () => {
  const sellStringCode = route.query.materialCode; // 改为通过销售单号查询

  if (!sellStringCode) {
    console.log("未获取到销售单号");
    return;
  }

  // 统一使用form.value来管理表单数据
  formData.materialCode = sellStringCode as string;

  // 获取入库单基本信息
  axios
    .get(`http://localhost:5202/api/Log/EditProductionPlanCommand`, {
      params: {
        MaterialCode: sellStringCode, // 确保后端API接收这个参数
      },
    })
    .then((res) => {
      if (res.data.data && res.data.data.length > 0) {
        const basicInfo = res.data.data[0];
        Object.assign(formData, {
          ...basicInfo,
        });
      }
    });

  // 获取产品信息
  axios
    .get(`http://localhost:5202/api/Log/EditMaterialsBliiProcurement`, {
      params: {
        MaterialCode: sellStringCode, // 确保后端API改为通过销售单号查询
      },
    })
    .then((res) => {
      dialogProductList.value = res.data.data.map((item) => ({
        materialsBliiId: item.materialsBliiId,
        materialCode: (route.query.materialCode as string) || "",
        demandquantity: Number(item.demandquantity),
        materialName: item.materialName,
        mainUnit: item.mainUnit,
        modelSpec: item.modelSpec,
        supplymode: item.supplymode,
        materialmethod: item.materialmethod,
        remark: item.remark,
      }));
    });
  axios
    .get(
      `http://localhost:5202/api/Log/EditMaterialsBliiProcurement?materialCode=${sellStringCode}`
    )
    .then((res) => {
      materialListData.value = res.data.data || []; // 填充物料清单表格数据
    });
  axios
    .get(
      `http://localhost:5202/api/Log/EditPlanReplenishMaterials?materialCode=${sellStringCode}`
    )
    .then((res) => {
      supplementaryListData.value = res.data.data || []; // 填充物料清单表格数据
    });
};
//补料添加
// 补料清单数据转后端命令对象
const convertToAddCommand = (item: any) => ({
  BillCode: item.billCode,
  BusinessType: item.businessType,
  BusinessStatus: item.businessStatus,
  MaterialCode: item.materialCode,
  MaterialName: item.materialName,
  BillStatus: item.billStatus || "开立", // 使用默认值
  MainUnit: item.mainUnit,
  Demandquantity: item.demandquantity,
  Supplymode: item.supplymode,
  Remark: item.remark,
  ReasonsForreplenishment: item.reasonsForreplenishment,
  ReasonsDate: item.reasonsDate
    ? dayjs(item.reasonsDate).format("YYYY-MM-DD")
    : null,
});
const handleAdds = async () => {
  // ... 原有保存逻辑 ...

  // 提交补料信息
  const supplementaryCommands =
    supplementaryListData.value.map(convertToAddCommand);
  if (supplementaryCommands.length > 0) {
    try {
      for (const cmd of supplementaryCommands) {
        const res = await axios.post(
          "http://localhost:5027/api/Log/AddPlanReplenishMaterials",
          cmd
        );
        if (res.data.code === 200) {
          // 假设 200 为成功码
          ElMessage.success("保存成功");
        }
      }
    } catch (error) {
      ElMessage.error(`补料提交失败：${error.message}`);
    }
  }
};
// interface ProductionPlan {
//   DocumentCode: string;
//   BusinessType: string;
//   Salesperson: string;
//   DocumentDate: string; // YYYY-MM-DD
//   Operator: string;
//   BusinessOrderNo: string;
//   VersionNumber: string;
//   DocumentStatus: string;
//   Auditor: string;
//   DeliveryDate: string; // YYYY-MM-DD
//   VersionDescription: string;
//   BusinessStatus: string;
//   AuditDate: string; // YYYY-MM-DD
//   Remark: string;
//   ProductionTotal: string;
// }

// interface PlanBillinfo {
//   MaterialCode: string;
//   MaterialName: string;
//   ModelSpec: string;
//   MainUnit: string;
//   Demandquantity: number;
//   Materialmethod: string;
//   Supplymode: string;
//   Workshop: string;
//   Status: boolean; // "启用" | "禁用"
// }

// interface PlanReplenishMaterials {
//   BillCode: string;
//   BusinessType: string;
//   BusinessStatus: string;
//   MaterialCode: string;
//   BillStatus: string;
//   MainUnit: string;
//   Demandquantity: number;
//   Supplymode: string;
//   Remark: string;
//   ReasonsForreplenishment: string;
//   ReasonsDate: string | null; // 允许空日期
// }

// interface ProcurementMateials {
//   MaterialCode: string;
//   MaterialName: string;
//   ModelSpec: string;
//   MainUnit: string;
//   Demandquantity: number;
//   ProcurementNum: number;
//   RequiredDate: string; // YYYY-MM-DD
//   ProcurementInstructions: string;
// }
// //修改
// interface UpdateMultiTableDataRequest {
//   ProductionPlan: ProductionPlan;
//   PlanReplenishMaterials: PlanReplenishMaterials;
//   ProcurementMateials: ProcurementMateials[];
//   PlanBillinfo: PlanBillinfo[];
// }
// const handleUpdate = async () => {
//   // 数据校验（示例，可根据需求扩展）
//   if (!formData.documentCode.trim()) {
//     ElMessage.error("单据编码不能为空");
//     return;
//   }

//   try {
//     // 整理主表数据（ProductionPlan）
//     const productionPlan: ProductionPlan = {
//       DocumentCode: formData.documentCode,
//       BusinessType: formData.businessType,
//       Salesperson: formData.salesperson,
//       DocumentDate: formData.documentDate
//         ? dayjs(formData.documentDate).format("YYYY-MM-DD")
//         : "",
//       Operator: formData.operator,
//       BusinessOrderNo: formData.businessOrderNo,
//       VersionNumber: formData.versionNumber,
//       DocumentStatus: formData.documentStatus,
//       Auditor: formData.auditor,
//       DeliveryDate: formData.deliveryDate
//         ? dayjs(formData.deliveryDate).format("YYYY-MM-DD")
//         : "",
//       VersionDescription: formData.versionDescription,
//       BusinessStatus: formData.businessStatus,
//       AuditDate: formData.auditDate
//         ? dayjs(formData.auditDate).format("YYYY-MM-DD")
//         : "",
//       Remark: formData.remark,
//       ProductionTotal: formData.productionTotal,
//     };

//     // 整理物料清单数据（PlanBillinfo）
//     const planBillinfo: PlanBillinfo[] = materialListData.value.map((item) => ({
//       MaterialCode: item.materialCode || "",
//       MaterialName: item.materialName || "",
//       ModelSpec: "", // 前端无此数据，根据实际补充
//       MainUnit: item.mainUnit || "",
//       Demandquantity: Number(item.productionQuantity) || 0, // 生产数量作为需求数量
//       Materialmethod: "", // 前端无此数据，根据实际补充
//       Supplymode: item.supplyMethod || "",
//       Workshop: item.workshop || "",
//       Status: item.status ? "启用" : "禁用", // 开关状态映射
//     }));

//     // 整理补料清单数据（PlanReplenishMaterials）
//     const planReplenishMaterials: PlanReplenishMaterials = {
//       BillCode: productionPlan.DocumentCode,
//       BusinessType: productionPlan.BusinessType,
//       BusinessStatus: productionPlan.BusinessStatus,
//       MaterialCode: "", // 根据实际逻辑填充
//       BillStatus: "", // 根据实际逻辑填充
//       MainUnit: "", // 根据实际逻辑填充
//       Demandquantity: 0, // 根据实际逻辑填充
//       Supplymode: "", // 根据实际逻辑填充
//       Remark: "", // 根据实际逻辑填充
//       ReasonsForreplenishment: "", // 根据实际逻辑填充
//       ReasonsDate: null, // 根据实际逻辑填充
//     };

//     // 整理订单信息数据（ProcurementMateials）
//     const procurementMateials: ProcurementMateials[] =
//       dialogProductList.value.map((item) => ({
//         MaterialCode: item.materialCode || "",
//         MaterialName: item.materialName || "",
//         ModelSpec: "", // 前端无此数据，根据实际补充
//         MainUnit: item.mainUnit || "",
//         Demandquantity: Number(item.quantity) || 0,
//         ProcurementNum: 0, // 初始采购数量
//         RequiredDate: dayjs().format("YYYY-MM-DD"), // 默认当前日期
//         ProcurementInstructions: "", // 前端无此数据，根据实际补充
//       }));

//     // 构造完整请求体
//     const requestBody: UpdateMultiTableDataRequest = {
//       ProductionPlan: productionPlan,
//       PlanReplenishMaterials: planReplenishMaterials,
//       ProcurementMateials: procurementMateials,
//       PlanBillinfo: planBillinfo,
//     };

//     // 调用后端API
//     const response = await axios.post<{ Code: string; Message: string }>(
//       "http://localhost:5027/api/Log/UpdateMultiTableData",
//       requestBody
//     );

//     if (response.data.Code === "修改成功") {
//       ElMessage.success("数据修改成功");
//       // 可选：重置表单或跳转页面
//       // router.push("/plan-list");
//     } else {
//       ElMessage.error(`修改失败：${response.data.Message}`);
//     }
//   } catch (error: any) {
//     console.error("修改失败", error);
//     ElMessage.error(`修改失败：${error.message || "网络请求失败"}`);
//   }
// };
onMounted(() => {
  handleView();
  searchProductsS();
});
</script>

<style scoped>
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}
.production-plan {
  padding: 10px;
}
.operation-bar {
  margin-bottom: 10px;
  text-align: right;
}
.basic-info {
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  padding: 10px;
}
.order-info,
.material-list,
.supplementary-list {
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  padding: 10px;
}
.el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
}
.el-form-item {
  width: 100%;
  text-align: left;
}
.el-form-item__label {
  text-align: left;
}
/* 表格内容垂直居中 */
.el-table__body tr td {
  vertical-align: middle;
}
/* 对话框内表格头部样式优化 */
.el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
}
</style>